package com.news.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.news.common.*;

import com.news.dao.impl.CmsArticleDaoImpl;
import com.news.entity.Article;
import com.news.entity.Comment;
import com.news.enums.Role;
import com.news.service.CmsArticleService;
import com.news.service.impl.CmsArticleServiceImpl;
import com.news.utils.DateUtils;
import com.news.utils.JsonUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Author:weiming
 * @Date:2021/4/1
 */
@WebServlet("/article/*")
public class ArticleServlet extends BaseServlet {

    private CmsArticleService cmsArticleService = new CmsArticleServiceImpl();

    /**
     * （管理端）分页获取文章
     * @param request
     * @param response
     */
    public void getAllArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (Role.Admin.getRoleCode()!=role){
            response.sendRedirect("admin?method=toLogin");
        }
        String pageNumStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("limit");
        if (pageNumStr == null || pageSizeStr == null){
            ServletResp.resp(response, CommonResult.validateFailed());
        }
        int pageSize = Integer.valueOf(pageSizeStr) ;
        int pageNum = Integer.valueOf(pageNumStr);
        pageNum = (pageNum-1) * pageSize;

        List<Article> allArticleInfo = cmsArticleService.getAllArticleInfo(pageNum, pageSize);
        if (allArticleInfo != null){
            String success = CommonPage.success(allArticleInfo);
            ServletResp.resp(response, success);
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * （管理端|客户端）查看文章详情
     * @param request
     * @param response
     */
    public void getArticleById(HttpServletRequest request, HttpServletResponse response) {
        String articleIdStr = request.getParameter("articleId");
        Integer articleId = Integer.valueOf(articleIdStr);
        Article article = cmsArticleService.getArticleById(articleId);
        System.out.println("request.getSession().getAttribute(\"role\") = " + request.getSession().getAttribute("role"));
        if (article != null){
            if(article.getIsShow() == 1 || request.getSession().getAttribute("role").equals(Role.Admin.getRoleCode())){
                ServletResp.resp(response, CommonResult.success(article));
            }else {
                ServletResp.resp(response, CommonResult.failed("文章不见了，去看看其他文章吧"));
            }

        }else {
            ServletResp.resp(response, CommonResult.failed("文章不存在"));
        }
    }

    /**
     * （管理端）获取投稿文章
     * @param request
     * @param response
     */
    public void getArticleByUser(HttpServletRequest request, HttpServletResponse response){
        String pageNumStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("limit");
        if (pageNumStr == null || pageSizeStr == null){
            ServletResp.resp(response, CommonResult.validateFailed());
        }
        int pageSize = Integer.valueOf(pageSizeStr);
        int pageNum = Integer.valueOf(pageNumStr);
        pageNum = (pageNum-1) * pageSize;

        List<Article> allArticleInfo = cmsArticleService.getArticleByUser(pageNum, pageSize);
        if (allArticleInfo != null){
            String success = CommonPage.success(allArticleInfo);
            ServletResp.resp(response, success);
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * （客户端|管理端）添加（投稿）文章
     * @param request
     * @param response
     */
    public void add(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        String userName = (String)request.getSession().getAttribute("userName");
        Integer role = (Integer) request.getSession().getAttribute("role");
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null){
            ServletResp.resp(response, CommonResult.unauthorized());
            //return;
        }
        // 根据角色
        int count = 0;
        article.setEditorId(userId);
        article.setRole(role);
        if (role == Role.Admin.getRoleCode()){
             article.setIsCheck(1);
             count = cmsArticleService.add(article);
        }else{
            // 用户需要审核才可以发布
            article.setIsCheck(0);
            count = cmsArticleService.add(article);
        }

        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * （管理端）更新文章
     * @param request
     * @param response
     */
    public void update(HttpServletRequest request, HttpServletResponse response){
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        int count = cmsArticleService.update(article);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (客户端)查询该分类下可以显示的文章列表
     * @param request
     * @param response
     */
    public void getArticleListByCatelogyId(HttpServletRequest request, HttpServletResponse response){
        String categoryIdStr = request.getParameter("categoryId");
        Integer categoryId = Integer.valueOf(categoryIdStr);
        Map<String,Object> map = cmsArticleService.getArticleListByCatelogyId(categoryId);
        if (map != null){
            ServletResp.resp(response, CommonResult.success(map));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * （管理端）删除文章
     * @param request
     * @param response
     */
    public void delete(HttpServletRequest request, HttpServletResponse response){
        String newsIdStr = request.getParameter("newsId");
        Integer newsId = Integer.valueOf(newsIdStr);
        int count = cmsArticleService.delete(newsId);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success("删除成功"));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * （客户端）跳转客户端投稿
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toPostNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.sendRedirect("postNewsDetail.html");
        //request.getRequestDispatcher("front/page/news/postNewsDetail.html").forward(request, response);
    }

    /**
     * （管理端）更新状态
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void changeCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        int count = cmsArticleService.changeCheck(article);
        if (count != 0){
            ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * (管理端)获取统计数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void getTotalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reqBody = JsonUtils.getJson(request);
        Article article = JsonUtils.fromJson(reqBody, Article.class);
        Map<String, Object> totalData = new CmsArticleDaoImpl().getTotalData();
        if (totalData != null){
            ServletResp.resp(response, CommonResult.success(totalData));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }

    /**
     * 上传文件
     * @param request
     * @param response
     * @throws IOException
     */
    public void uploadFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
        SmartUpload su=new SmartUpload();
        try{

            su.initialize(this.getServletConfig(), request,response);
            su.upload();
            File file = su.getFiles().getFile(0);
            String filePath  =
                    request.getSession().getServletContext().getRealPath("/")+ "upload\\";
            java.io.File path = new java.io.File(filePath);
            if (!path.exists()){
                System.out.println("文件夹不存在，创建文件夹");
                path.mkdir();
            }
            String filename = file.getFileName();
            String str = filename.substring(filename.lastIndexOf("."), filename.length());
            System.out.println(filename);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String finalname  = sdf.format(new Date()) + str;
            System.out.println("filePath + finalname = " + filePath + finalname);
            file.saveAs(filePath + finalname , File.SAVEAS_PHYSICAL);
            Map<String,Object> map = new HashMap<>();
            map.put("title",filename);
            map.put("src", "/news/upload/"+finalname);
            int result = new CmsArticleDaoImpl().uploadFile(map);
            if (result == 1) {
                ServletResp.resp(response, CommonResult.result(0, "文件上传成功", map));
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            ServletResp.resp(response, CommonResult.failed("文件上传失败"));
        }
    }

    /**
     * （客户端）搜索功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void getSearchResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        List<Map<String, Object>> searchResult = new CmsArticleDaoImpl().getSearchResult(title);
        if (searchResult != null){
            ServletResp.resp(response, CommonResult.success(searchResult));
        }else {
            ServletResp.resp(response, CommonResult.failed());
        }
    }




}
